<script>
  import config from './config'
  import { getToken } from '@/utils/auth'
  import {pushCallback} from '@/api/push'
  import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update.js'
  const dicAudioName = [
    {value: 'needHelp', label: '接到工单求助', src: '/static/audio/needHelp.mp3'},
    {value: 'newRepair', label: '接到新的报修', src: '/static/audio/newRepair.mp3'},
    {value: 'newRepairOrder', label: '接到新的维修工单', src: '/static/audio/newRepairOrder.mp3'},
    {value: 'repairFinish', label: '您发起的报修已完成', src: '/static/audio/repairFinish.mp3'}
  ]
  export default {
    onLaunch: function() {
      this.initApp()
      // #ifdef APP-PLUS
      if (getToken()) {
        plus.push.getClientInfoAsync(info => {
          pushCallback({cid: info.clientid})
        })
      }
      let timer = null
      plus.push.addEventListener('click', (message) => {
        clearTimeout(timer)
        if (!message || !message.payload) {
          return
        }
        timer = setTimeout(() => {
          if(message.payload.hospitalId !== this.$store.getters.curHospitalId){
            uni.reLaunch({
              url: `/pages/mine/change-hospital-dialog?hospitalId=${message.payload.hospitalId}&path=${message.payload.pagePath}`
            })
          }else{
            uni.reLaunch({
              url: message.payload.pagePath || '/pages/tabbar/home/home'
            })
          }
        }, 0)
      })
      plus.push.addEventListener('receive', (message) => {
        console.log(message)
        if (message && typeof message.payload === 'object' && !message.payload.createByApp) {
          plus.push.createMessage(message.payload.body || '您有新的消息',
            Object.assign({}, message.payload, {createByApp: true}),
            {
              cover: false,
              title: message.payload.title || '消息提醒',
            })
          const audioSrc = dicAudioName.find(item => item.value === message.payload.audioName)?.src
          if (audioSrc) {
            const audio = uni.createInnerAudioContext()
            audio.src = audioSrc
            audio.play()
          }
        }
      })
      // #endif
    },
    methods: {
      // 初始化应用
      async initApp() {
        // 初始化应用配置
        this.initConfig()
        // 检查用户登录状态
        try {
          await this.checkLogin()
        } finally {
          checkUpdate()
        }
      },
      initConfig() {
        this.globalData.config = config
      },
      checkLogin() {
        return new Promise((resolve) => {
          if (!getToken()) {
            uni.reLaunch({
              url: '/pages/login',
              complete: () => {
                resolve()
              }
            })
          } else {
            resolve()
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  @import "uview-ui/index.scss";
  @import '@/static/scss/index.scss';
</style>
